package pl.edu.agh.neuraleconomy.core.simulation;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import pl.edu.agh.neuraleconomy.model.exchange.Company;
import pl.edu.agh.neuraleconomy.model.exchange.Exchange;
import pl.edu.agh.neuraleconomy.model.simulation.Simulation;
import pl.edu.agh.neuraleconomy.persistence.base.DaoProvider;

public class SimulationService {
	Logger logger = Logger.getLogger(getClass());
	
	public boolean isHoliday(Date date){
		List<Exchange> todaysExchanges = DaoProvider.getExchangeDao().getByDate(date);
		return todaysExchanges.isEmpty();
	}

	public BigDecimal getSharePrice(Company company, Date date) {
		Exchange todays = DaoProvider.getExchangeDao().getByCompanyAndDate(company.getId(), date);
		if (todays != null) {
			if (todays.getOpeningPrice().compareTo(BigDecimal.ZERO) > 0) {
				return todays.getOpeningPrice();
			}
		}

		return DaoProvider.getExchangeDao().getLatestByCompanyBeforeDate(company.getId(), date).getClosingPrice().setScale(2);
	}

	public void saveSimulation(SimulationEngine simulation) {
		logger.info("Saving simulation: " + simulation.toString());
		DaoProvider.getSimulationDao().save(simulation);

		for (DailyHistory hist : simulation.getHistory()) {
			DaoProvider.getDailyHistoryDao().save(hist);
		}

		for (Transaction transaction : simulation.getTransactions()) {
			DaoProvider.getTransactionDao().save(transaction);
		}

		for (Share share : simulation.getSharesMap().values()) {
			if (share.getAmount() == 0) {
				DaoProvider.getShareDao().tryDelete(share);
			} else {
				DaoProvider.getShareDao().save(share);
			}
		}
	}

	public SimulationEngine load(Long id) {
		logger.info("Loading simulation: " + id);
		Simulation sim = DaoProvider.getSimulationDao().getById(id);

		SimulationEngine engine = new SimulationEngine(sim);

		for (pl.edu.agh.neuraleconomy.model.simulation.DailyHistory history : DaoProvider.getDailyHistoryDao().getForSimulation(id)) {
			engine.getHistory().add(new DailyHistory(history));
		}

		for (pl.edu.agh.neuraleconomy.model.simulation.Transaction transaction : DaoProvider.getTransactionDao().getForSimulation(id)) {
			engine.getTransactions().add(new Transaction(transaction));
		}

		for (pl.edu.agh.neuraleconomy.model.simulation.Share share : DaoProvider.getShareDao().getForSimulation(id)) {
			engine.getSharesMap().put(share.getCompany(), new Share(share));
		}

		return engine;
	}

}
